package com.app.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.common.ApplyTool;
import com.app.common.ElectronicMsgTool;
import com.app.common.PersonMsgTool;
import com.app.common.SystemConstant;
import com.app.mapper.ApplyMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.StringTool;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.LevelVo;
import com.app.vo.OutNapeVo;
import com.app.vo.PersonVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

@Slf4j
@RestController
@Controller
@RequestMapping("/api/person")
public class PersonController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private PersonService personService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private PersonPositionService personPositionService;
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private PersonResumeService personResumeService;
    @Autowired
    private PersonCheckService personCheckService;
    @Autowired
    private PersonFamilyService personFamilyService;
    @Autowired
    private DepartmentService departmentService;
    ;

    @GetMapping("/getDropList")//下拉框查询
    public Result<Object> getDropList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String[] categoryArr = {"民族", "政治面貌", "学历", "人员类型", "专业技术职务", "年度考评等次", "家庭关系称谓", "行政职务", "待遇级别"};
        CategoryVo vo = new CategoryVo();
        for (int i = 0; i < categoryArr.length; i++) {
            //input(民族) get(id)
            CategoryModel CateGorymodel = categoryService.getPersonCate(categoryArr[i]);//通过name拿到category的id
            List<CategoryModel> categoryModelList1 = categoryService.getCategoryByPid(CateGorymodel.getId());//根据id查询pid为id的list
            if (i == 0) {
                vo.setNationList(categoryModelList1);
            } else if (i == 1) {
                vo.setZzmmList(categoryModelList1);
            } else if (i == 2) {
                vo.setEducationList(categoryModelList1);
            } else if (i == 3) {
                vo.setPersonTypeList(categoryModelList1);
            } else if (i == 4) {
                vo.setPositionTecList(categoryModelList1);
            } else if (i == 5) {
                vo.setYearCheckList(categoryModelList1);
            } else if (i == 6) {
                vo.setFamilyList(categoryModelList1);
            } else {
                vo.setTreatmentLevelList(categoryModelList1);
            }
        }
        return Result.success(vo);
    }

    @GetMapping("/getPersonList")//人员管理分页查询
    //todo 士兵没有传单位信息，查不到数据
    public Result<Object> getPersonList(PersonModel personModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<CategoryModel> categoryModelList = categoryService.getListByPid();//查出所有pid不等于0且status等于1
        HashMap<Integer, String> map = new HashMap<>();
        for (CategoryModel model : categoryModelList) {
            map.put(model.getId(), model.getName());//键值对存进map
        }
        List<Integer> idList = null;
        if (user.getDepartmentId() != 1) {
            idList = departmentService.getDepId(user.getDepartmentId());
        }
        String[] str;
        Page<PersonModel> personModelPage = personService.getPagePersonList(personModel, idList, null);
        if (personModelPage.getRecords() == null) {
            return Result.error(200, "暂无数据");
        }
        for (int i = 0; i < personModelPage.getRecords().size(); i++) {
            if (personModelPage.getRecords().get(i).getDepartmentId() != null) {
                DepartmentModel departmentModel1 = departmentService.getDepByDepId(personModelPage.getRecords().get(i).getDepartmentId());
                if (departmentModel1 != null) {
                    personModelPage.getRecords().get(i).setDepartmentText(departmentModel1.getName());
                }//部门名称
            }
            personModelPage.getRecords().get(i).setPersonTypeText((String) map.get(personModelPage.getRecords().get(i).getPersonType()));//人员类型字段
            List<PersonCheckModel> checkModelList = personCheckService.getCheckList(personModelPage.getRecords().get(i).getId());
            List<String> checkDesc = new ArrayList<>();
            String checkDesc2 = null;
            for (PersonCheckModel personCheckModel : checkModelList) {
                CategoryModel categoryModel = categoryService.getCategoryById(personCheckModel.getCheckResult());
                personCheckModel.setCheckResultText(categoryModel.getName());//结果字段
                checkDesc.add(personCheckModel.getYear() + categoryModel.getName());
                String checkDesc1 = StringTool.strip(String.valueOf(checkDesc), "[]");
                checkDesc2 = checkDesc1.replaceAll(",", "、");
            }
            personModelPage.getRecords().get(i).setCheckDesc(checkDesc2);//把考核结果放进一个list后返回
            if (!checkModelList.isEmpty()) {
                personModelPage.getRecords().get(i).setCheckList(checkModelList);
            }
            List<PersonFamilyModel> familyModelList = personFamilyService.getFamilyList(personModelPage.getRecords().get(i).getId());
            for (PersonFamilyModel personFamilyModel : familyModelList) {
                CategoryModel categoryModel = categoryService.getCategoryById(personFamilyModel.getZzmm());
                personFamilyModel.setZzmmText(categoryModel.getName());//政治面貌字段
                CategoryModel categoryModel1 = categoryService.getCategoryById(personFamilyModel.getAppellation());
                personFamilyModel.setAppellationText(categoryModel1.getName());//称谓字段
            }
            if (!familyModelList.isEmpty()) {
                personModelPage.getRecords().get(i).setFamilyList(familyModelList);
            }
            QueryWrapper<ApplyModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("person_id", personModelPage.getRecords().get(i).getId());
            List<ApplyModel> applyModels = applyMapper.selectList(queryWrapper);
            List<LevelVo> levelVoList = ApplyTool.LEVEL_VO_LIST;
            for (ApplyModel applyModel : applyModels) {
                LocalDateTime start = applyModel.getStartTime().toLocalDateTime();
                LocalDateTime end = applyModel.getEndTime().toLocalDateTime();
                long between = ChronoUnit.DAYS.between(start, end);
                applyModel.setDays(between + 1);
                for (LevelVo levelVo : levelVoList) {
                    if (applyModel.getType().equals(levelVo.getId())) {
                        applyModel.setTypeText(levelVo.getLevelName());
                    }
                }
            }
            if (!applyModels.isEmpty()) {
                personModelPage.getRecords().get(i).setLeaveList(applyModels);
            }
            List<PersonResumeModel> resumeModelList = personResumeService.getResumeList(personModelPage.getRecords().get(i).getId());
            for (PersonResumeModel personResumeModel : resumeModelList) {
                personResumeModel.setTimeRange(personResumeModel.getStartTime() + " " + "--" + " " + personResumeModel.getEndTime());
            }
            if (!resumeModelList.isEmpty()) {
                personModelPage.getRecords().get(i).setResumeList(resumeModelList);
            }
            AdminUserModel person = adminUserService.getUserByPersonId(personModelPage.getRecords().get(i).getId());
            if (person != null) {
                personModelPage.getRecords().get(i).setIsHost(person.getRoles());
            }
        }
        int count = (int) personModelPage.getTotal();
        List<PersonModel> personModelList = personModelPage.getRecords();
        PersonVo vo = new PersonVo();
        vo.setCount(count);
        vo.setList(personModelList);
        return Result.success(vo);
    }

    @PostMapping("/insertPerson")
    public Result<Object> insertPerson(@RequestBody PersonModel personModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        try {
            if (personModel.getId() > 0) {
                personModel.setUpdateTime(CommonHelp.getNowTimestamp());
                personService.update(personModel);
                //考核删除
                if (StrUtil.isNotBlank(personModel.getCheckRemove())) {
                    String[] checkRemoveArr = personModel.getCheckRemove().split(",");
                    for (int i = 0; i < checkRemoveArr.length; i++) {
                        personCheckService.delete(Integer.parseInt(checkRemoveArr[i]));
                    }
                }
                //考核新增
                if (personModel.getCheckAdd() != null && !personModel.getCheckAdd().isEmpty()) {
                    for (PersonCheckModel personCheckModel : personModel.getCheckAdd()) {
                        personCheckModel.setPersonId(personModel.getId());
                        personCheckModel.setCreateTime(CommonHelp.getNowTimestamp());
                        personCheckService.insert(personCheckModel);
                    }
                }
                //简历删除
                if (StrUtil.isNotBlank(personModel.getResumeRemove())) {
                    String[] resumeRemoveArr = personModel.getResumeRemove().split(",");
                    for (int i = 0; i < resumeRemoveArr.length; i++) {
                        personResumeService.delete(Integer.parseInt(resumeRemoveArr[i]));
                    }
                }
                //简历新增
                if (personModel.getResumeAdd() != null && !personModel.getResumeAdd().isEmpty()) {
                    for (PersonResumeModel personResumeModel : personModel.getResumeAdd()) {
                        personResumeModel.setPersonId(personModel.getId());
                        personResumeModel.setCreateTime(CommonHelp.getNowTimestamp());
                        personResumeService.insert(personResumeModel);
                    }
                }
                //简历编辑
                if (personModel.getResumeEdit() != null && !personModel.getResumeEdit().isEmpty()) {
                    for (PersonResumeModel personResumeModel : personModel.getResumeEdit()) {
                        PersonResumeModel resumeModel = personResumeService.getById(personResumeModel.getId());
                        if (resumeModel != null) {
                            resumeModel.setContent(personResumeModel.getContent());
                            resumeModel.setStartTime(personResumeModel.getStartTime());
                            resumeModel.setEndTime(personResumeModel.getEndTime());
                            resumeModel.setUpdateTime(CommonHelp.getNowTimestamp());
                            personResumeService.update(resumeModel);
                        }
                    }
                }
                //家庭删除
                if (StrUtil.isNotBlank(personModel.getFamilyRemove())) {
                    String[] familyRemoveArr = personModel.getFamilyRemove().split(",");
                    for (String s : familyRemoveArr) {
                        personFamilyService.delete(Integer.parseInt(s));
                    }
                }
                //家庭新增
                if (personModel.getFamilyAdd() != null && !personModel.getFamilyAdd().isEmpty()) {
                    for (PersonFamilyModel personFamilyModel : personModel.getFamilyAdd()) {
                        personFamilyModel.setPersonId(personModel.getId());
                        personFamilyModel.setCreateTime(CommonHelp.getNowTimestamp());
                        personFamilyService.insert(personFamilyModel);
                    }
                }
                //家庭编辑
                if (personModel.getFamilyEdit() != null && !personModel.getFamilyEdit().isEmpty()) {
                    for (PersonFamilyModel personFamilyModel : personModel.getFamilyEdit()) {
                        PersonFamilyModel familyModel = personFamilyService.getById(personFamilyModel.getId());
                        if (familyModel != null) {
                            familyModel.setAppellation(personFamilyModel.getAppellation());
                            familyModel.setMemberName(personFamilyModel.getMemberName());
                            familyModel.setBirthday(personFamilyModel.getBirthday());
                            familyModel.setPhone(personFamilyModel.getPhone());
                            familyModel.setUnit(personFamilyModel.getUnit());
                            familyModel.setZzmm(personFamilyModel.getZzmm());
                            personFamilyModel.setUpdateTime(CommonHelp.getNowTimestamp());
                            personFamilyService.update(familyModel);
                        }
                    }
                }
                //请假删除
                if (StrUtil.isNotBlank(personModel.getLeaveRemove())) {
                    String[] applyRemoveArr = personModel.getLeaveRemove().split(",");
                    for (String s : applyRemoveArr) {
                        applyMapper.deleteById(Integer.parseInt(s));
                    }
                }
                //请假新增
                if (personModel.getLeaveList() != null && !personModel.getLeaveList().isEmpty()) {
                    for (ApplyModel applyModel : personModel.getLeaveList()) {
                        if (applyModel.getId() == null) {
                            applyModel.setPersonId(personModel.getId());
                            applyModel.setCreateTime(CommonHelp.getNowTimestamp());
                            applyMapper.insert(applyModel);
                        }
                    }
                }
                //请假编辑
                if (personModel.getLeaveEdit() != null && !personModel.getLeaveEdit().isEmpty()) {
                    for (ApplyModel applyModel : personModel.getLeaveEdit()) {
                        ApplyModel model1 = applyMapper.selectById(applyModel.getId());
                        if (model1 != null) {
                            model1.setType(applyModel.getType());
                            model1.setReason(applyModel.getReason());
                            model1.setStartTime(applyModel.getStartTime());
                            model1.setEndTime(applyModel.getEndTime());
                            model1.setArea(applyModel.getArea());
                            model1.setUpdateTime(CommonHelp.getNowTimestamp());
                            applyMapper.updateById(model1);
                        }
                    }
                }
                //同步账号
                AdminUserModel adminUserModel = adminUserService.getUserByPersonId(personModel.getId());
                if (adminUserModel != null) {
                    if (!adminUserModel.getAccount().contains(personModel.getName())) {
                        adminUserModel.setAccount(personModel.getName());
                        adminUserModel.setRealName(personModel.getName());
                    }
                    if (!adminUserModel.getDepartmentId().equals(personModel.getDepartmentId())) {
                        adminUserModel.setDepartmentId(personModel.getDepartmentId());
                    }
                    adminUserService.update(adminUserModel);
                } else {
                    AdminUserModel adminModel = new AdminUserModel();
                    adminModel.setAccount(personModel.getName());
                    adminModel.setRealName(personModel.getName());
                    adminModel.setDepartmentId(personModel.getDepartmentId());
                    adminModel.setRoles(0);
                    adminModel.setPersonId(personModel.getId());
                    String salt = "gz_b";
                    String pwd1 = md5Hex("jsxl_123456" + salt);
                    adminModel.setPwd(pwd1);
                    adminModel.setStatus(1);
                    adminModel.setCreateTime(CommonHelp.getNowTimestamp());
                    adminUserService.insert(adminModel);
                }
            } else {
                //新增人员
                personModel.setCreateTime(CommonHelp.getNowTimestamp());
                personService.insert(personModel);
                //添加账号
                AdminUserModel adminUserModel = new AdminUserModel();
                adminUserModel.setRoles(0);
                adminUserModel.setPersonId(personModel.getId());
                adminUserModel.setAccount(personModel.getName());
                String salt = "gz_b";
                String pwd1 = md5Hex("jsxl_123456" + salt);
                adminUserModel.setPwd(pwd1);
                adminUserModel.setRealName(personModel.getName());
                adminUserModel.setStatus(1);
                adminUserModel.setDepartmentId(personModel.getDepartmentId());
                adminUserService.insert(adminUserModel);
                //考核新增
                if (personModel.getCheckList() != null && !personModel.getCheckList().isEmpty()) {
                    for (PersonCheckModel personCheckModel : personModel.getCheckList()) {
                        personCheckModel.setPersonId(personModel.getId());
                        personCheckModel.setCreateTime(CommonHelp.getNowTimestamp());
                        personCheckService.insert(personCheckModel);
                    }
                }
                //家庭新增
                if (personModel.getFamilyList() != null && !personModel.getFamilyList().isEmpty()) {
                    for (PersonFamilyModel personFamilyModel : personModel.getFamilyList()) {
                        personFamilyModel.setPersonId(personModel.getId());
                        personFamilyModel.setCreateTime(CommonHelp.getNowTimestamp());
                        personFamilyService.insert(personFamilyModel);
                    }
                }
                //简历新增
                if (personModel.getResumeList() != null && !personModel.getResumeList().isEmpty()) {
                    for (PersonResumeModel personResumeModel : personModel.getResumeList()) {
                        personResumeModel.setPersonId(personModel.getId());
                        personResumeModel.setCreateTime(CommonHelp.getNowTimestamp());
                        personResumeService.insert(personResumeModel);
                    }
                }
                //请假新增
                if (personModel.getLeaveList() != null && !personModel.getLeaveList().isEmpty()) {
                    for (ApplyModel applyModel : personModel.getLeaveList()) {
                        applyModel.setPersonId(personModel.getId());
                        applyModel.setCreateTime(CommonHelp.getNowTimestamp());
                        applyMapper.insert(applyModel);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("有异常：" + e);
        }
        return Result.success(null);
    }

    @PostMapping("/updatePersonSort")//排序
    public Result<Object> updatePersonSort(
            @RequestBody JSONObject json,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String strIds = json.get("ids").toString();
        String sorts = json.get("sorts").toString();
        if (strIds != null && !strIds.isEmpty() && sorts != null && !sorts.isEmpty()) {
            String[] str = strIds.split(",");
            String[] strSort = sorts.split(",");
            for (int i = 0; i < str.length; i++) {
                PersonModel model = personService.selectPersonById(Integer.parseInt(str[i]));
                model.setSort(Integer.valueOf(strSort[i]));
                personService.update(model);
            }
        }
        return Result.success("操作成功");
    }

    @GetMapping("/selectPersonById")//单查人员信息、现职务、简历
    public Result<Object> selectPersonById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        PersonModel model = personService.selectPersonById(id);
        if (model != null) {
            PersonPositionModel posModel = personPositionService.selectPosByPid(id);
            if (posModel != null) {
                DepartmentModel depModel = departmentService.getDepByDepId(posModel.getDepartmentId());
                posModel.setDepName(depModel.getName());
                model.setPositionText(posModel);//主职
            } else {
                model.setPositionText(null);
            }
            List<PersonResumeModel> resumeModelList = personResumeService.getResumeList(id);
            if (resumeModelList != null) {
                model.setResumeList(resumeModelList);//简历列表
            } else {
                model.setResumeList(null);
            }

            return Result.success(model);
        }
        return Result.error(500, "暂无此人员信息");
    }

    @GetMapping("/updatePersonStatus")//修改状态
    public Result<Object> updateStatus(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        PersonModel personModel = personService.selectPersonById(id);
        if (personModel == null) {
            return Result.error(500, "该人员不存在");
        }
        personModel.setId(id);
        personModel.setStatus(0);
        personService.update(personModel);
        AdminUserModel userByPersonId = adminUserService.getUserByPersonId(id);
        if (userByPersonId != null) {
            adminUserService.delete(userByPersonId.getId());
        }
        return Result.success(null);
    }

    @GetMapping("/deleteById")//删除角色
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        PersonModel personModel = personService.selectPersonById(id);
        if (personModel == null) {
            return Result.error(500, "该角色不存在");
        } else {
            personService.delete(id);
            return Result.success(null);
        }
    }

    /**
     * 人员的批量删除
     * @param ids
     * @param request
     * @return
     */
    @DeleteMapping("/deletePersonBatchByIds")
    public Result<Object> deletePersonBatchByIds(@RequestParam("ids") String ids, HttpServletRequest request){
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return personService.deletePersonBatchByIds(ids);
    }
    // 校验token并获取用户信息的方法
    private AdminUserModel validateTokenAndGetUser(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            throw new IllegalArgumentException("token不存在");
        }
        String userId = TokenUtils.verify(token);
        return adminUserService.getUserByUserId(Integer.parseInt(userId));
    }

    @GetMapping("/deleteByIds")//批量删除角色
    public Result<Object> deleteByIds(
            @RequestParam("ids") String ids,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String[] split = ids.split(",");
        for (String s : split) {
            try {
                personService.delete(Integer.parseInt(s));
            } catch (Exception e) {
                log.info(e.toString());
            }
        }
        return Result.success(null);
    }

    /**
     * 人员信息批量导出
     *
     * @param json
     * @param response
     */
    @PostMapping("/getPlaceByCusExcel")
    public void getPlaceByCusExcel(
            @RequestBody JSONObject json,
            HttpServletResponse response, HttpServletRequest request) {
        if (json.containsKey("titles") && StrUtil.isNotBlank(json.get("titles").toString())) {
            String titles = json.get("titles").toString();
            String personId = json.get("personId").toString();
            List<String> idsList = Arrays.asList(personId.split(","));
            List<PersonModel> modelList = personService.newListExport(idsList);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String[] arr = titles.split(",");//字符串转数组
            XSSFWorkbook xssfSheets = formGeneration2(modelList, arr);
            String fileName = "人员基本信息花名册.xlsx";
            OutputStream outputStream = null;
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
                //设置ContentType请求信息格式
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName);
                outputStream = response.getOutputStream();
                xssfSheets.write(outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if (json.containsKey("personId") && json.get("personId") != null) {
                String personId = json.get("personId").toString();
                List<PersonModel> personModels = new ArrayList<>();
                List<PersonModel> personModels1 = new ArrayList<>();
                String[] split = personId.split(",");
                for (int i = 0; i < split.length; i++) {
                    PersonModel personModel = personService.selectById(Integer.parseInt(split[i]));
                    if (personModel.getPersonType() == 31) {//干部
                        personModels.add(personModel);
                    }
                    if (personModel.getPersonType() == 87) {//战士
                        personModels1.add(personModel);
                    }
                }

                Map<String, Object> map = Maps.newHashMap();
                if (!personModels.isEmpty()) {
                    map.put("personModels", personModels);
                }
                if (!personModels1.isEmpty()) {
                    map.put("personModels1", personModels1);
                }
                String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm"));
                String fileName = "人员信息花名册" + time;
                try {
                    TemplateExportParams params = new TemplateExportParams(SystemConstant.PersonExportURL, true);
                    exportExcel(params, map, fileName, response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public XSSFWorkbook formGeneration2(List<PersonModel> modelList, String[] idsArr) {//idsArr 勾选框传进来的值
        //查询数据库中的数据
        XSSFWorkbook xssfSheets = new XSSFWorkbook();
        XSSFSheet userList = xssfSheets.createSheet("list");

        Row titleRow = userList.createRow(0);//创建第一行，起始为0
        XSSFCellStyle cellStyle = xssfSheets.createCellStyle();
        XSSFFont font = xssfSheets.createFont();
        font.setBold(true);
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short) 12);
        titleRow.setHeight((short) (30 * 20));
        cellStyle.setFont(font);
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        cellStyle.setAlignment(HorizontalAlignment.CENTER); //⽔平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        for (int i = 0; i < idsArr.length; i++) {
            for (int j = 0; j < PersonMsgTool.PERSON_MSG_VO_LIST.size(); j++) {
                if (idsArr[i].equals(PersonMsgTool.PERSON_MSG_VO_LIST.get(j).getKey())) {
                    titleRow.createCell(i).setCellValue(PersonMsgTool.PERSON_MSG_VO_LIST.get(j).getTitle());
                    titleRow.getCell(i).setCellStyle(cellStyle);
                    userList.setColumnWidth(i, 5120);
                }
            }
        }
        XSSFCellStyle cellStyle2 = xssfSheets.createCellStyle();
        XSSFFont font2 = xssfSheets.createFont();
        cellStyle2.setFont(font2);
        cellStyle2.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        cellStyle2.setAlignment(HorizontalAlignment.CENTER); //⽔平居中
        cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        for (int i = 0; i < modelList.size(); i++) {
            Row row = userList.createRow(i + 1);//设置对哪一行操作
            for (int j = 0; j < idsArr.length; j++) {
                if (idsArr[j].equals("name")) {
                    if (modelList.get(i).getName() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getName());
                    }
                } else if (idsArr[j].equals("gender")) {
                    if (modelList.get(i).getGender() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getGender());
                    }
                } else if (idsArr[j].equals("birthday")) {
                    if (modelList.get(i).getGender() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getBirthday());
                    }
                } else if (idsArr[j].equals("nation")) {
                    if (modelList.get(i).getNationText() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getNationText());
                    } else {
                        row.createCell(j).setCellValue("");
                    }
                } else if (idsArr[j].equals("nativePlace")) {
                    if (modelList.get(i).getNativePlace() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getNativePlace());
                    }
                } else if (idsArr[j].equals("birthPlace")) {
                    if (modelList.get(i).getBirthPlace() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getBirthPlace());
                    }
                } else if (idsArr[j].equals("rdTime")) {
                    if (modelList.get(i).getRdTime() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getRdTime());
                    }
                } else if (idsArr[j].equals("joinWorkTime")) {
                    if (modelList.get(i).getJoinWorkTime() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getJoinWorkTime());
                    }
                } else if (idsArr[j].equals("isHealth")) {
                    if (modelList.get(i).getIsHealth() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getIsHealth());
                    } else {
                        row.createCell(j).setCellValue("");
                    }
                } else if (idsArr[j].equals("educationText")) {
                    if (modelList.get(i).getEducationText() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getEducationText());
                    } else {
                        row.createCell(j).setCellValue("");
                    }
                } else if (idsArr[j].equals("major")) {
                    row.createCell(j).setCellValue(modelList.get(i).getMajor());
                } else if (idsArr[j].equals("school")) {
                    row.createCell(j).setCellValue(modelList.get(i).getSchool());
                } else if (idsArr[j].equals("personType")) {
                    if (modelList.get(i).getPersonType() != null) {
                        CategoryModel categoryModel = categoryService.getCategoryById(modelList.get(i).getPersonType());
                        row.createCell(j).setCellValue(categoryModel.getName());
                    } else {
                        row.createCell(j).setCellValue("");
                    }
                } else if (idsArr[j].equals("rwTime")) {
                    row.createCell(j).setCellValue(modelList.get(i).getRwTime());
                } else if (idsArr[j].equals("positionLevel")) {
                    row.createCell(j).setCellValue(modelList.get(i).getPositionLevel());
                } else if (idsArr[j].equals("rankTitle")) {
                    row.createCell(j).setCellValue(modelList.get(i).getRankTitle());
                } else if (idsArr[j].equals("positionDesc")) {
                    if (modelList.get(i).getPositionDesc() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getPositionDesc());
                    } else {
                        row.createCell(j).setCellValue("");
                    }
                } else if (idsArr[j].equals("isSpecial")) {
                    if (modelList.get(i).getIsSpecial() != null) {
                        row.createCell(j).setCellValue(modelList.get(i).getIsSpecial());
                    } else {
                        row.createCell(j).setCellValue("");
                    }
                } else if (idsArr[j].equals("phone")) {
                    row.createCell(j).setCellValue(modelList.get(i).getPhone());
                } else if (idsArr[j].equals("idcard")) {
                    row.createCell(j).setCellValue(modelList.get(i).getIdcard());
                } else if (idsArr[j].equals("address")) {
                    row.createCell(j).setCellValue(modelList.get(i).getAddress());
                } else if (idsArr[j].equals("treatmentLevel")) {
                    row.createCell(j).setCellValue(modelList.get(i).getTreatmentLevel());
                }
                row.getCell(j).setCellStyle(cellStyle2);
            }
        }
        return xssfSheets;
    }

    @GetMapping("/getPersonTitleList")//获取导出项目
    public Result<Object> getPersonTitleList(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        OutNapeVo vo = new OutNapeVo();
        vo.setPersonTitleList(PersonMsgTool.PERSON_MSG_VO_LIST);
        vo.setElectronicTitleList(ElectronicMsgTool.ELECTRONIC_MSG_VO_LIST);
        return Result.success(vo);
    }

    public static void exportExcel(TemplateExportParams
                                           params, Map<String, Object> map, String
                                           fileName, HttpServletResponse response) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        downLoadExcel(fileName, response, workbook);
    }

    private static void downLoadExcel(String fileName, HttpServletResponse
            response, Workbook workbook) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName + ".xls", "UTF-8"));
            ServletOutputStream outStream = null;
            try {
                outStream = response.getOutputStream();
                workbook.write(outStream);

            } finally {
                if (outStream != null) {
                    outStream.flush();
                    outStream.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
